package com.aiatomic.couting;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.aiatomic.couting.util.HttpUtils;
import com.aiatomic.couting.util.SystemUtil;
import com.aiatomic.couting.util.ValidatorUtils;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

public class RegisterActivity extends Activity {
	private Button submit;
	private Handler handler = new Handler();
	private String msg = "发生未知错误";
	private TextView phone;
	private TextView txtPassword;
	private EventHandler eh;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		initSMS();
		TextView txtBack = (TextView) this.findViewById(R.id.txtBack);
		txtBack.setText(R.string.back);
		txtBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
		TextView txtNext = (TextView) this.findViewById(R.id.txtNext);
		txtNext.setVisibility(View.INVISIBLE);
		submit = (Button) findViewById(R.id.btn_reg_submit);
		phone = (TextView) findViewById(R.id.reg_phone);
		txtPassword = (TextView) findViewById(R.id.reg_password);
		TextView txtMiddle = (TextView) this.findViewById(R.id.txtMiddle);
		txtMiddle.setText(R.string.new_user_register);
		bindEvent();
	}

	private void bindEvent() {
		final Button btn_sm = (Button) this.findViewById(R.id.get_sms);

		this.findViewById(R.id.get_sms).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (ValidatorUtils.isMobileNO(phone.getText().toString())) {
					btn_sm.setEnabled(false);
					CountDownTimer timer = new CountDownTimer(CoutingApplication.SMS_TIME, 1000) {

						@Override
						public void onTick(long millisUntilFinished) {
							String txtRepeat = String.format(getResources().getString(R.string.repeat_sms_code),
									millisUntilFinished / 1000);
							btn_sm.setText(txtRepeat);
						}

						@Override
						public void onFinish() {
							btn_sm.setText(R.string.get_sms_code);
							btn_sm.setEnabled(true);
						}
					};
					timer.start();

					SMSSDK.getVerificationCode("86", phone.getText().toString());

				} else {
					phone.setError(getResources().getString(R.string.err_input_phone));
					phone.setFocusable(true);
				}

			}
		});

		submit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

//				TextView txtSmsCode = (TextView) findViewById(R.id.sms_code);
//				if (txtSmsCode.getText().toString().isEmpty()) {
//					txtSmsCode.setError(getResources().getString(R.string.err_input_sms_code));
//					txtSmsCode.setFocusable(true);
//					return;
//				}
				if (!ValidatorUtils.isMobileNO(phone.getText().toString())) {
					phone.setError(getResources().getString(R.string.err_input_phone));
					phone.setFocusable(true);
					return;
				}
				if (ValidatorUtils.isCorrectPassword(txtPassword.getText().toString())) {
//					SMSSDK.submitVerificationCode("86", phone.getText().toString(),
//							txtSmsCode.getText().toString().trim());
					s_reg();
					RegisterActivity.this.submit.setEnabled(false);
				} else {
					txtPassword.setError(getResources().getString(R.string.err_input_password));
					txtPassword.setFocusable(true);
				}
			}
		});
	}

	private void s_reg() {
		Map<String, String> params = new HashMap<String, String>();
		params.put("pwd", RegisterActivity.this.txtPassword.getText().toString());
		params.put("imei", SystemUtil.getIMEI(RegisterActivity.this));
		params.put("device",
				SystemUtil.getDeviceBrand() + ";" + SystemUtil.getSystemModel() + ";" + SystemUtil.getSystemVersion());
		params.put("mobile", RegisterActivity.this.phone.getText().toString());
		params.put("platform", String.valueOf(IConstant.PLATFORM));
		params.put("channel", String.valueOf(IConstant.CHANNEL_MOB));
		params.put("sign", HttpUtils.md5(params.get("pwd") + params.get("mobile") + params.get("imei")
				+ params.get("device") + params.get("platform") + params.get("channel") + IConstant.NORMAL_MD5_KEY));
		HttpUtils.post(new Handler() {

			@Override
			public void handleMessage(Message msg) {
				if (msg.what == HttpUtils.CODE_SUCCESS_RQ_100) {
					try {
						JSONObject json = new JSONObject(msg.obj.toString());
						Toast toast = Toast.makeText(RegisterActivity.this, json.getString("msg"), Toast.LENGTH_LONG);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
						if (json.getInt("code") == HttpUtils.RET_SUCCESS) {
							RegisterActivity.this.finish();
						} else {
							RegisterActivity.this.submit.setEnabled(true);
						}
					} catch (JSONException e) {
						e.printStackTrace();
						Log.e("", msg.obj.toString());
						Toast toast = Toast.makeText(RegisterActivity.this,
								RegisterActivity.this.getResources().getString(R.string.server_format_error),
								Toast.LENGTH_LONG);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
						RegisterActivity.this.submit.setEnabled(true);
					}
				} else if (msg.what == HttpUtils.CODE_ERROR_RQ_999) {
					RegisterActivity.this.submit.setEnabled(true);
					Toast toast = Toast.makeText(RegisterActivity.this, ICodeMsg.ERROR_CODES_HTTP.get(msg.what),
							Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
				}
			}

		}, IConstant.CENTER + "/v/Account_c/account_m_create/", params);
	}

	private void initSMS() {

		SMSSDK.setAskPermisionOnReadContact(true);
		// 3.0版本之后的初始化看这里（包括3.0）
		eh = new EventHandler() {

			@Override
			public void afterEvent(int event, int result, Object data) {
				if (result == SMSSDK.RESULT_COMPLETE) {
					// 回调完成
					if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
						handler.post(new Runnable() {
							@Override
							public void run() {
								RegisterActivity.this.s_reg();
							}
						});
						// 提交验证码成功
					} else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
						System.out.println(data);
						// 获取验证码成功
					} else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
						// 返回支持发送验证码的国家列表
					}
				} else {

					Throwable e = (Throwable) data;
					e.printStackTrace();
					try {
						JSONObject err = new JSONObject(e.getMessage());
						int status = err.getInt("status");
						if (ICodeMsg.ERROR_CODES_SMS.containsKey(status)) {
							msg = ICodeMsg.ERROR_CODES_SMS.get(status);
						}
					} catch (JSONException e1) {
						e1.printStackTrace();
					}
					handler.post(new Runnable() {
						@Override
						public void run() {
							RegisterActivity.this.submit.setEnabled(true);
							Toast toast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG);
							toast.setGravity(Gravity.CENTER, 0, 0);
							toast.show();

						}
					});

				}
			}
		};
		SMSSDK.registerEventHandler(eh); // 注册短信回调
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (eh != null) {
			SMSSDK.unregisterEventHandler(eh);
		}
	}

}
